import express from 'express';
import {MongoDB} from "./handlers/MongoDB";
import bodyParser from 'body-parser'
import {ApiAnswer} from "./handlers/ApiAnswer";


const server = express();
server.use(bodyParser.json())

const port = 9587;
const db = new MongoDB();

const urlencodedParser = express.urlencoded({extended: false});

server.post("/add/:collection", urlencodedParser, (request, response) => {
    db.saveRecord({
        collection: request.params.collection,
        documents: request.body
    }).finally(() => {
        ApiAnswer.returnTrueEmptyAnswer(response)
    })

});


server.post("/clean/:collection", urlencodedParser, (request, response) => {
    ApiAnswer.catchErrorAnswer(db.cleanCollection(request.params.collection).then(res => {
        ApiAnswer.returnTrueEmptyAnswer(response)
    }), response);
});

server.post("/delete/:collection", urlencodedParser, async (request, response) => {
    ApiAnswer.catchErrorAnswer(db.deleteDocumentFromCollection(request.params.collection, request.body).then(res => {
        ApiAnswer.returnTrueEmptyAnswer(response)
    }), response);
});

server.get("/get/:collection", urlencodedParser, (request, response) => {
    ApiAnswer.catchErrorAnswer(db.getRecord(request.params.collection).then(res => {
        ApiAnswer.returnAnswerWithValue(res, response)
    }), response);

});

server.get("/list", urlencodedParser, (request, response) => {
    db.getList().then(res => {
        ApiAnswer.returnAnswerWithValue(res, response)
    })

});

server.listen(port, () => {
    console.info(`Server started on PORT ${port}`)
});